﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using MyOS.Models;
using MyOS.Utils;
using MyOS.ViewModel;
using MyOS.Views.ChildView;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;

namespace MyOS.Views
{
    /// <summary>
    ///     VirtualDisk.xaml 的交互逻辑
    /// </summary>
    public partial class VirtualDiskView : UserControl
    {
        private readonly FileStream readFileStream;
        private char diskName;
        private string fileName;
        private string folderName;

        public VirtualDiskView()
        {
            InitializeComponent();
            try
            {
                IFormatter formatter = new BinaryFormatter();
                readFileStream = new FileStream("objMenuItem", FileMode.Open);
                ViewModel = (FileViewModel) formatter.Deserialize(readFileStream);
                readFileStream.Close();
            }
            catch (Exception e)
            {
                DiskUtils.saveObjectToFile(new FileViewModel());
            }

            setDiskState('C');
            setDiskState('D');
            DataContext = ViewModel;
        }

        private FileViewModel ViewModel { get; }

        private void 新建文本文档_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            var window = new NewFileView("C", diskName);

            if (item.TypeName == 'e')
            {
                MessageBoxX.Show("只能在文件夹内建立文件！", "Error", Application.Current.MainWindow,
                    MessageBoxButton.OK, new MessageBoxXConfigurations
                    {
                        OKButton = "好的",
                        MinHeight = 180,
                        MinWidth = 300,
                        MessageBoxIcon = MessageBoxIcon.Error,
                        ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                    });
            }
            else
            {
                if (Application.Current.MainWindow == null) return;
                ((MainWindow) Application.Current.MainWindow).IsMaskVisible = true;
                window.ShowDialog();
                ((MainWindow) Application.Current.MainWindow).IsMaskVisible = false;
                if (window.isSuccess)
                    item.MenuItems.Add(new FileTreeViewItemModel(window.fileName, 'e', "\uf0f6"));
                DiskUtils.saveObjectToFile(ViewModel);
            }

            setDiskState(diskName);
        }

        private void 新建文件夹_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            var window = new NewFolderView();
            window.getFolderName += SetFolderName;
            if (Application.Current.MainWindow == null) return;
            ((MainWindow) Application.Current.MainWindow).IsMaskVisible = true;
            window.ShowDialog();
            ((MainWindow) Application.Current.MainWindow).IsMaskVisible = false;
            if (folderName != null)
            {
                if (DiskUtils.searchIsExists(diskName, folderName, 'd') != -1)
                {
                    MessageBoxX.Show("同名文件夹已存在！", "Error", Application.Current.MainWindow,
                        MessageBoxButton.OK, new MessageBoxXConfigurations
                        {
                            OKButton = "好的",
                            MinHeight = 180,
                            MinWidth = 300,
                            MessageBoxIcon = MessageBoxIcon.Error,
                            ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                        });
                }
                else
                {
                    var attrBytes = new byte[20];
                    var folderNameBytes = Encoding.Default.GetBytes(folderName);
                    for (var i = 0; i < folderNameBytes.Length; i++) attrBytes[i] = folderNameBytes[i];

                    attrBytes[3] = Convert.ToByte('d');
                    attrBytes[4] = 3;
                    attrBytes[5] = Convert.ToByte(0); //起始盘块号
                    //6 7 为长度，文件夹没有长度 默认为0
                    attrBytes[8] = Convert.ToByte(DateTime.Now.ToString("yy")); //创建时间
                    attrBytes[9] = Convert.ToByte(DateTime.Now.Month);
                    attrBytes[10] = Convert.ToByte(DateTime.Now.Day);
                    attrBytes[11] = Convert.ToByte(DateTime.Now.Hour);
                    attrBytes[12] = Convert.ToByte(DateTime.Now.Minute);
                    attrBytes[13] = Convert.ToByte(DateTime.Now.Second);
                    DiskUtils.writeToRoot(diskName, attrBytes);
                    Notice.Show("保存成功！", "Success", 3, MessageBoxIcon.Success);
                    item.MenuItems.Add(new FileTreeViewItemModel(folderName, 'd', "\uf07b"));
                    DiskUtils.saveObjectToFile(ViewModel);
                    var FileCount = IniUtils.ReadInteger("Disk" + diskName, "RecordCount", 0, "./config.ini");
                    IniUtils.WriteInteger("Disk" + diskName, "RecordCount", ++FileCount, "./config.ini");
                }
            }

            setDiskState(diskName);
        }

        private void 打开_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            if (item.TypeName == 'e')
            {
                var state = DiskUtils.readFile(diskName, item.FileName);
                switch (state)
                {
                    case -1:
                        MessageBoxX.Show("文件不可读", "Error", Application.Current.MainWindow,
                            MessageBoxButton.OK, new MessageBoxXConfigurations
                            {
                                OKButton = "好的",
                                MinHeight = 180,
                                MinWidth = 300,
                                MessageBoxIcon = MessageBoxIcon.Error,
                                ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                            });
                        break;
                    case -2:
                        MessageBoxX.Show("未找到文件！", "Error", Application.Current.MainWindow,
                            MessageBoxButton.OK, new MessageBoxXConfigurations
                            {
                                OKButton = "好的",
                                MinHeight = 180,
                                MinWidth = 300,
                                MessageBoxIcon = MessageBoxIcon.Error,
                                ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                            });
                        break;
                    default:
                        TextEditor.Text = DiskUtils.file;
                        break;
                }
            }
        }

        private void 移动_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            if (item.TypeName == 'r')
            {
                MessageBoxX.Show("不能移动根目录！", "Error", Application.Current.MainWindow,
                    MessageBoxButton.OK, new MessageBoxXConfigurations
                    {
                        OKButton = "好的",
                        MinHeight = 180,
                        MinWidth = 300,
                        MessageBoxIcon = MessageBoxIcon.Error,
                        ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                    });
            }
            else
            {
                var window = new MoveFileVIew(item, diskName, ViewModel);
                if (Application.Current.MainWindow == null) return;
                ((MainWindow) Application.Current.MainWindow).IsMaskVisible = true;
                window.ShowDialog();
                ((MainWindow) Application.Current.MainWindow).IsMaskVisible = false;
                DiskUtils.saveObjectToFile(ViewModel);
            }
        }

        private void 重命名_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            var window = new RenameView();
            window.getFileName += SetFileName;
            if (Application.Current.MainWindow == null) return;
            ((MainWindow) Application.Current.MainWindow).IsMaskVisible = true;
            window.ShowDialog();
            ((MainWindow) Application.Current.MainWindow).IsMaskVisible = false;
            if (fileName != null)
            {
                if (!DiskUtils.rename(diskName, fileName, item.FileName, item.TypeName)) //返回了false说明有同名文件了
                {
                    MessageBoxX.Show(item.TypeName == 'e' ? "同名文件已存在！" : "同名文件夹已存在！", "Error",
                        Application.Current.MainWindow,
                        MessageBoxButton.OK, new MessageBoxXConfigurations
                        {
                            OKButton = "好的",
                            MinHeight = 180,
                            MinWidth = 300,
                            MessageBoxIcon = MessageBoxIcon.Error,
                            ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                        });
                }
                else
                {
                    Notice.Show("重命名成功！", "Success", 3, MessageBoxIcon.Success);
                    setDiskState('C');
                    setDiskState('D');
                    item.FileName = fileName;
                }
            }
            else
            {
                Notice.Show("未改动!", "Info", 3, MessageBoxIcon.Info);
            }
        }

        private void 删除_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            if (item.TypeName == 'r')
            {
                MessageBoxX.Show("不能删除默认根路径！", "Error", Application.Current.MainWindow,
                    MessageBoxButton.OK, new MessageBoxXConfigurations
                    {
                        OKButton = "好的",
                        MinHeight = 180,
                        MinWidth = 300,
                        MessageBoxIcon = MessageBoxIcon.Error,
                        ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                    });
            }
            else
            {
                var isDeleted = DiskUtils.delete(diskName, item.FileName, item.TypeName);
                if (isDeleted)
                {
                    deleteFromModel(item.FileName, item.TypeName,
                        diskName == 'C' ? ViewModel.DiskCModel : ViewModel.DiskDModel);
                    DiskUtils.saveObjectToFile(ViewModel);
                    Notice.Show("删除成功！", "Success", 3, MessageBoxIcon.Success);
                }
            }

            setDiskState(diskName);
        }

        private void 属性_Click(object sender, RoutedEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            switch (item.TypeName)
            {
                case 'r':
                    break;
                case 'd':
                case 'e':
                    var window = new AttributeView(item.FileName, DiskUtils.readFileAttribute(diskName,
                        DiskUtils.searchIsExists(diskName, item.FileName, item.TypeName)));
                    if (Application.Current.MainWindow == null) return;
                    ((MainWindow) Application.Current.MainWindow).IsMaskVisible = true;
                    window.ShowDialog();
                    ((MainWindow) Application.Current.MainWindow).IsMaskVisible = false;
                    break;
            }
        }

        private void TvMenu_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
        }

        private void TvMenu_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            var item = (FileTreeViewItemModel) TvMenu.SelectedItem;
            try
            {
                if (item.FileName.Equals("本地磁盘C"))
                    diskName = 'C';
                else if (item.FileName.Equals("本地磁盘D")) diskName = 'D';
            }
            catch (Exception exception)
            {
                e.Handled = false;
            }
        }

        private void SetFolderName(string value)
        {
            folderName = value;
        }

        private void SetFileName(string value)
        {
            fileName = value;
        }

        private void deleteFromModel(string fileName, char fileType, FileTreeViewItemModel item)
        {
            for (var i = 0; i < item.MenuItems.Count; i++)
                if (item.MenuItems[i].FileName == fileName && item.MenuItems[i].TypeName.Equals(fileType)) //找到了文件/文件夹
                {
                    item.MenuItems.RemoveAt(i);
                    return;
                }
                else
                {
                    deleteFromModel(fileName, fileType, item.MenuItems[i]);
                }
        }

        private void setDiskState(char diskName)
        {
            var state = DiskUtils.readDiskBlockState(diskName);
            var box = new SolidColorBrush[state.Length];
            var DiskImageGrid = diskName == 'C' ? DiskCImageGrid : DiskDImageGrid;
            var row = box.Length / 8;
            DiskImageGrid.Children.Clear();
            for (var i = 0; i < row; i++)
            {
                DiskImageGrid.RowDefinitions.Add(new RowDefinition());
                for (var j = 0; j < 8; j++)
                {
                    switch (state[i * 8 + j])
                    {
                        case 2:
                            box[i * 8 + j] = new SolidColorBrush(Colors.DeepSkyBlue);
                            break;
                        case 1:
                            box[i * 8 + j] = new SolidColorBrush(Colors.Red);
                            break;
                        case 0:
                            box[i * 8 + j] = new SolidColorBrush(Colors.Green);
                            break;
                    }

                    DiskImageGrid.ColumnDefinitions.Add(new ColumnDefinition());

                    var StackPanel = new StackPanel();
                    var Rectangle = new Rectangle();
                    var TextBlock = new TextBlock();
                    StackPanel.Children.Add(Rectangle);
                    StackPanel.Children.Add(TextBlock);
                    StackPanel.Orientation = Orientation.Vertical;
                    StackPanel.Margin = new Thickness(10);
                    Rectangle.Fill = box[i * 8 + j];
                    Rectangle.Width = 20;
                    Rectangle.Height = 20;
                    TextBlock.Text = (i * 8 + j).ToString();
                    TextBlock.FontSize = 14;
                    TextBlock.Width = 18;
                    TextBlock.Height = 18;
                    TextBlock.HorizontalAlignment = HorizontalAlignment.Center;

                    //diskCImageViewModel.Items.Add(new DiskImageModel(i, box[i]));
                    DiskImageGrid.Children.Add(StackPanel);
                    Grid.SetRow(StackPanel, i);
                    Grid.SetColumn(StackPanel, j);
                }
            }
        }
    }
}